const input = document.querySelector("input");
const img = document.querySelector("#avatar");
const mask = document.querySelector(".mask");
const clipImg = document.querySelector("#clip-img");
const confirmBtn = document.querySelector("#clip-btn");
const cancelBtn = document.querySelector("#cancel-btn");

let cropper = null;

input.addEventListener("change", (e) => {
  const file = e.target.files[0];

  const url = URL.createObjectURL(file);
  clipImg.src = url;
  mask.classList.remove("hidden");
  /**
   * 使用第三方库进行图片裁剪
   */
  cropper = new Cropper(clipImg, {
    dragMode: "move",
    aspectRatio: 1,
    autoCropArea: 0.9,
    restore: false,
    guides: false,
    center: false,
    highlight: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false,
  });
});

cancelBtn.addEventListener("click", () => {
  mask.classList.add("hidden");
});

confirmBtn.addEventListener("click", () => {
  const imgUrl = cropper.getCroppedCanvas().toDataURL("image/jpeg");

  img.src = imgUrl;
  mask.classList.add("hidden");
});
